"""
fastapi 服务
"""
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from googletrans import Translator
from services.api_wrap import async_api_wrapper, BaseResponse
from fastapi import Body
from loguru import logger
import json


def create_app():
    app = FastAPI(title="AIChat API Server", version='1.0')
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    mount_chat_routes(app)
    return app


translator = Translator()


@async_api_wrapper
async def translate_api(
        input_text: str = Body(description='文本', examples=None),
        from_lan: str = Body(description='源语言'),
        to_lan: str = Body(description='目标语言'),
):
    # 语言翻译
    trans_text = translator.translate(input_text, src=from_lan, dest=to_lan)
    # 输出结果
    result = {
        '原文': input_text,
        '源语言': from_lan,
        '目标语言': to_lan,
        '译文': trans_text,
    }
    logger.info(json.dumps(result, ensure_ascii=False, indent=4))
    return BaseResponse(data=result)

def mount_chat_routes(app: FastAPI):

    app.post(
        path='/translate', summary="东盟语言翻译"
    )(translate_api)

my_app = create_app()


if __name__ == '__main__':
    uvicorn.run(app=my_app, host="0.0.0.0", port=6006, reload=False)
